const https = require('https')
const { formatTime } = require('./util')
const sqlhelper = require('./sqlhelper')
//雪花算法生成ID
const snowflake = require('./snowflake')



const multer  = require('multer')
const storage = multer.diskStorage({
  destination: './uploads',
    filename: function (req, file, cb) {
     //获取图片类型
     let fileType = file.originalname.split('.')
     fileType = fileType[fileType.length - 1]
     cb(null, snowflake()  + '.' + fileType)
    
   }
 })

 const upload = multer({ storage: storage })

///tokens缓存
let tokens = {}

module.exports = function (app) {
  //登录拦截中间件
  function loginRouter(req,res,next) {
    if (req.method.toUpperCase() == 'OPTIONS') {
      next()
      return;
    }
    let token = req.headers.token
    if (token) {
      sqlhelper(`select * from session where id = '${token}' and state = 1`).then(ret => {
        if (ret.length) {
          let session = ret[0]
          //2H
          if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
            req.session = {
              userId: session.userId,
              userName: session.userName
            }
            next()
          } else {
            res.status(400).send({ errorMsg: '登录超时' })
          }

        } else {
          res.status(400).send({ errorMsg: '当前用户未登录' })
        }
      })
    } else {
      res.status(400).send({ errorMsg: '缺少token,请先进行登录' })
    }
    let session = tokens[req.headers.token]
  }

  //让初登录以为的所有小程序接口都先验证登录
  app.use('/admin', loginRouter)
  
  //文件上传
   app.post('/upload',upload.single('file'),(req,res) =>{
       res.send(req.file)
   })

  //管理后台登录.
  app.post('/login', (req,res,next) => {
    let userName = req.body.userName
    let passWord = req.body.passWord
    if (userName && passWord) {
      sqlhelper(`
         select * from user where userName = '${userName}'
    `).then(users => {
        if (users.length) {  //正常登录
          let user = users[0]
          if (passWord == user.passWord) {
            let token = snowflake()
            //缓存到tokens到session表
            // console.log(user.nickName);
            sqlhelper(`
    INSERT INTO session(id,userId,userName,inTime,createTime,platform) 
    values('${token}','${user._id}','${user.nickName}','${formatTime(new Date())}','${new Date().getTime()}', 'admin')
  `).then(ret => {
              res.send({
                nickName: user.nickName,
                token,
                avatarUrl: user.photo,
                _id: user._id
              })
            })
          } else {
            res.send({ errorMsg: '密码错误' })
          }
        } else {
          res.send({ errorMsg: '当前用户不存在' })
        }
      })
    } else {
      res.send({ errorMsg: '用户名和密码不能为空' })
    }
  })

  //退出登录
  app.get('/admin/logout', (req, res) => {
    sqlhelper(`
      update session set outTime = '${formatTime(new Date())}',state = 0
      where id = '${req.headers.token}'
  `).then(ret => {
      res.send({ msg: '退出登陆成功' })
    })
  })


  //修改密码
  app.post('/admin/changePassWord', (req,res) => {
    let userId = req.session.userId
    let passWord = req.body.passWord
    let newPassWord = req.body.newPassWord
    if (passWord && newPassWord) {
      //查询用户
      sqlhelper(`select passWord from user where _id = '${userId}' `).then(users => {
        let user = users[0]
        //比对原密码
        if (user.passWord == passWord) {
          //修改密码
          sqlhelper(`update user set passWord = '${newPassWord}' where _id = '${userId}'`).then(ret => {
            res.send({ Msg: '修改密码成功' })
          })
        } else {
          res.send({ errorMsg: '原密码错误' })
        }
      })
    } else {
      res.send({ errorMsg: '原密码和新密码不能为空' })
    }
  })

  //分页获取首页项目列表  
  //pageSize 每页数据量大小 默认10
  //pageNum 当前页 默认1
  //offset = (pageNum - 1)*pageSize
  //type 类型 非必填 banner ，轮播图 category,分类 recomend,为您推荐, 不填搜索全部
  app.get('/admin/index', (req,res) => {
    let pageSize = req.query.pageSize || 10
    let pageNum = req.query.pageNum || 1
    let offset = (pageNum - 1) * pageSize
    let title = req.query.title
    let type = req.query.type
    let wheresql = 'from index_region where state = 1'
    //按类型查询
    if (type) wheresql += ` and type = '${type}'`
    //按标题关键字搜索
    if (title) wheresql += ` and title like "%${title}%"`
    sqlhelper(`
    select count(*) as total ${wheresql};
    select * ${wheresql}
    limit ${pageSize} offset ${offset}
    `).then(ret => {
      res.send({
        total: ret[0][0].total,
        rows: ret[1]
      })
    })
  })


  //新增首页项目
  //img 图片地址必填
  //title 标题 轮播图不填，其他必填
  //url 连接地址 非必填
  //status 是否启用 非必填 1,启用，0，停用
  //type 类型 非必填 banner (默认)，轮播图 category,分类 recomend,为您推荐
  app.post('/admin/index', (req,res) => {
    let img = req.body.img, url = req.body.url, status = req.body.status
    let type = req.body.type || 'banner', title = req.body.title
    if (type != 'banner' && !title) {
      res.send({ errorMsg: '标题不能为空' })
      return
    }
    if (status != 1) status = 0 //默认启用
    if (img) {
      let createTime = new Date().getTime()
      sqlhelper(`
      INSERT INTO index_region(title,img,url,status,state,createTime,unitId,type) 
      VALUES('${title}','${img}','${url}','${status}',1,${createTime},'juzao','${type}')
    `).then(ret => {
        res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: '新增数据失败' })
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

  //修改首页项目
  //indexId 主码_id 必填
  app.put('/admin/index', (req,res) => {
    if (req.body.indexId) {
      ///需要修改的项
      let updateTime = new Date().getTime()
      let updateKey = ['img', 'url', 'title', 'status']
      let updateValues = [`updateTime = ${updateTime}`]
      for (let i = 0; i < updateKey.length; i++) {
        let key = updateKey[i], value = req.body[key]
        if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
      }
      sqlhelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })


  //删除地址  逻辑删除
  //addressId 主码_id 必填
  app.delete('/admin/index', (req,res) => {
    let indexId = req.query.indexId
    if (indexId) {
      sqlhelper(`
          UPDATE index_region
          set state = 0
          WHERE _id = ${indexId}
        `).then(ret => {
        res.send(ret)
      })
    } else {
      res.send({ errorMsg: '传入参数错误' })
    }
  })

}